import cx from 'classnames';
import React, { useEffect, useState } from 'react';
import Input from '../../../../Input';
import { prefix } from '../../../../config';
import { useDebounce } from '../../../../hooks';
import { getPrefixCls } from '../../../../utils';
import type { EditableCell } from './type';

export interface EditableModalProps extends EditableCell {
  onSelectData: () => void;
}
const cellPrefixCls = getPrefixCls(prefix.editableTable, 'cell');

export default function EditableModal(props: EditableModalProps) {
  const {
    align,
    columnId,
    value,
    curModalParams,
    onChange,
    onBlur,
    onSelectData,
    onClick,
    onDoubleClick,
    onMouseEnter,
    onMouseLeave,
    ...restProps
  } = props;

  const [inputValue, setInputValue] = useState(value);
  const debouncedValue = useDebounce(inputValue, { wait: 300 });
  useEffect(() => {
    inputValue !== value &&
      inputValue === debouncedValue &&
      onChange(debouncedValue);
  }, [value, inputValue, debouncedValue]);

  return (
    <div className={`${cellPrefixCls}__modal`}>
      <Input
        className={cx(
          `${cellPrefixCls}__modal--input`,
          `${cellPrefixCls}__component`,
          align,
        )}
        {...restProps}
        bordered={false}
        value={inputValue}
        onChange={(e) => setInputValue(e.target.value)}
        onBlur={() => onBlur()}
        // onClick={onClick && onClick.bind(this, columnId)}
        // onDoubleClick={onDoubleClick && onDoubleClick.bind(this, columnId)}
        // onMouseEnter={onMouseEnter && onMouseLeave.bind(this, columnId)}
        // onMouseLeave={onMouseLeave && onClick.bind(this, columnId)}
      />
      <div
        className={`${cellPrefixCls}__modal--icon`}
        onClick={(e) => {
          onSelectData();
          onClick && onClick({ id: columnId, params: curModalParams }, e);
        }}
        onDoubleClick={
          onDoubleClick &&
          onDoubleClick.bind(this, { id: columnId, params: curModalParams })
        }
        onMouseEnter={
          onMouseEnter &&
          onMouseLeave.bind(this, { id: columnId, params: curModalParams })
        }
        onMouseLeave={
          onMouseLeave &&
          onClick.bind(this, { id: columnId, params: curModalParams })
        }
      >
        . . .
      </div>
    </div>
  );
}
